<?php

namespace app\common\command;
use app\lib\MessageBus\base\AmqpBus;
use app\lib\MessageBus\BusPassenger;
use think\console\Input;
use think\console\Output;
use think\console\input\Option;
use think\console\Command;

class MessageBus extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('message_bus')
            ->addOption('bus', null, Option::VALUE_REQUIRED, 'bus name')
            ->setDescription('启动消费');
    }

    /**
     * 0.监听所有事件   php think message_bus --bus all
     *   i.只建议测试环境、开发环境使用,此种模式dump输出在log里面,控制台看不到dump
     *   ii.因为生成了所有事件进程,如果非docker环境注意退出进程之后,所有进程需要手动kill,否则有可能一直挂起进程
     *
     * 1.用户登录事件监听   php think message_bus --bus member-login
     *
     * 2.订单支付事件监听  php think message_bus --bus order-paid
     *
     * 3.订单创建事件监听  php think message_bus --bus order-create
     *
     * @param Input $input
     * @param Output $output
     * @return string|void
     */
    protected function execute(Input $input, Output $output)
    {
        if ($input->hasOption('bus')) {
            $bus = $input->getOption('bus');
        } else {
           return "指令错误";
        }
        ini_set ("memory_limit","-1");
        if($bus == 'all') {
                $log_file = __DIR__ . "/../../../runtime/log/".date("Ym")."/".date("d").".log";
                $all_bus = '';
                foreach (BusPassenger::instance()->getBus() as $bus_one) {
                    $all_bus .=  "&php think message_bus --bus ".$bus_one .">>".$log_file;
                }
                $command = trim($all_bus,"&");
                shell_exec($command);
            }else {
                while (true) {
                    AmqpBus::instance()->start($bus);  //启动
                }
        }
    }
}